import React,{useReducer} from 'react';

export const initialState ={count:0};

function reducer(state,action){
    switch(action.type){
        case 'increment':
            return {count:state.count+1};
        case 'decrement':
            return {count:state.count-1};
        default:
            throw new Error();
    }
}
export default()=>{
    //使用useReducer函数创建状态state以及更新状态的dispatch函数
    const [state,dispatch]=useReducer(reducer,initialState);
    return(
        <>
            Count:{state.count}
            <br/>
            <button onClick={()=>dispatch({type:'increment'})}>+</button>
            <button onClick={()=>dispatch({type:'decrement'})}>-</button>
        </>
    );
}


// 语法：const [state, dispatch] = useReducer(reducer, initialArg, init);

// 作为useState的替代方案。接受类型为(state, action) => newState的reducer函数,并返回与dispatch方法配对的当前状态

// 注意：当你涉及多个子值的复杂 state(状态) 逻辑时，useReducer 通常优于 useState 。